# user_manager.py
import os
import json
import bcrypt
from datetime import datetime


class UserManager:
    def __init__(self, users_file="data/users.json"):
        self.users_file = users_file
        self.users = {}
        self.initialize_database()

    def initialize_database(self):
        """初始化用户数据库"""
        # 确保数据目录存在
        os.makedirs(os.path.dirname(self.users_file), exist_ok=True)

        # 如果文件不存在，创建空文件
        if not os.path.exists(self.users_file):
            with open(self.users_file, "w") as f:
                json.dump({}, f)

        # 加载现有用户数据
        self.load_users()

    def load_users(self):
        """从JSON文件加载用户数据"""
        try:
            if os.path.exists(self.users_file):
                with open(self.users_file, "r") as f:
                    self.users = json.load(f)
            else:
                self.users = {}
        except Exception as e:
            print(f"加载用户数据出错: {e}")
            self.users = {}

    def save_users(self):
        """保存用户数据到JSON文件"""
        try:
            with open(self.users_file, "w") as f:
                json.dump(self.users, f, indent=2)
            return True
        except Exception as e:
            print(f"保存用户数据出错: {e}")
            return False

    def _hash_password(self, password):
        """使用bcrypt安全哈希密码"""
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

    def _verify_password(self, input_password, hashed_password):
        """验证密码是否匹配"""
        return bcrypt.checkpw(input_password.encode('utf-8'), hashed_password.encode('utf-8'))

    def register_user(self, username, password):
        """注册新用户"""
        if not username or not password:
            return False, "用户名和密码不能为空"

        if len(username) < 4:
            return False, "用户名至少需要4个字符"

        if len(password) < 6:
            return False, "密码至少需要6个字符"

        # 检查用户名是否已存在
        if username in self.users:
            return False, "用户名已存在"

        # 创建新用户
        self.users[username] = {
            "password_hash": self._hash_password(password),
            "created_at": datetime.now().isoformat(),
            "last_login": None
        }

        # 保存到文件
        if self.save_users():
            return True, "注册成功"
        else:
            # 回滚内存中的更改
            self.users.pop(username, None)
            return False, "注册失败，请重试"

    def verify_user(self, username, password):
        """验证用户登录"""
        if not username or not password:
            return False, "请输入用户名和密码"

        user_data = self.users.get(username)
        if not user_data:
            return False, "用户不存在"

        if not self._verify_password(password, user_data["password_hash"]):
            return False, "密码错误"

        # 更新最后登录时间
        user_data["last_login"] = datetime.now().isoformat()
        self.save_users()

        return True, "登录成功"